<template>
    <div class="container">
        <div class="tool">
            <!-- 搜索列表 -->
            <div class="search">
            <el-button type="success" @click="searchAll" style="margin-right: 10px;">{{ $t("message.queryAll") }}</el-button>
            <el-date-picker
                v-model="queryParmas.queryDate"
                type="date"
                :placeholder="$t('message.selectDate')"
                :disabled-date="disabledDate"
            />
            <el-button type="primary" @click="toSearch" class="query">{{ $t("message.DateQuery") }}</el-button>
          </div>
          <!-- 数据下载 -->
          <div class="downloadExe">
            <el-select v-model="selectDate" :placeholder="$t('message.choose')">
                <el-option
                v-for="item in options"
                    :key="item.rid"
                    :label="item.currentDate"
                    :value="item.currentDate"
                >
                </el-option>
            </el-select>
            <el-button type="success" :icon="Edit" style="margin-left: 10px;" @click="download" :loading="exportLoading">
                {{ exportLoading ? '导出中...' : '' }}
            </el-button>
          </div>
        </div>
   
        <!-- 数据列表 -->
        <div class="table">
            <div class="table-container">
                <el-table 
                :data="stateList"
                border 
                stripe
                max-height="calc(100vh - 280px)"
            >
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column width="160px">
                        <template #header>
                            {{ $t("message.datetime") }}
                        </template>
                        <template #default="{row}">
                            {{ filterDate(row.createdAt)  }}
                        </template>
                    </el-table-column>
                    <el-table-column width="320px" sortable prop="gateway_name" label="网关">
                          <template #default="{row}">
                            {{ gateway_store.gatewayNameMap(row.gateway_ip)? gateway_store.gatewayNameMap(row.gateway_ip): "网关未连接"  }} {{row.gateway_ip}}
                        </template>
                    </el-table-column>
                    <el-table-column v-for="(item,index) in propList" :key="index" :prop="item.prop" :label="$t(item.label)" :width="item.prop == 'module_id'? 320: item.prop == 'uvc'? 250: ''" >

                        <template v-if="item.prop === 'uvc'" #default="{row}">
                            <el-link type="primary" @click="showUvcDetail(row)">{{ row.uvc }}</el-link>
                        </template>
                        <template v-else-if="item.prop === 'module_id'" #default="{row}">
                            {{ getDeviceName(row.gateway_ip, row.module_id) }}
                        </template>
                        <template v-else #default="{row}">
                            {{ row[item.prop] }}
                        </template>
                    </el-table-column>
               </el-table>
            </div>
             <div class="pagination-wrapper">
                 <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="queryParmas.pageSize"
                    :page-sizes="[10, 15]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
             </div>
        </div>
        <el-dialog v-model="uvcDialogVisible" title="紫外详细数据" width="500px">
            <div v-if="uvcDetail.length">
                <el-table :data="uvcDetail" border size="small">
                    <el-table-column prop="time" label="采样时间" width="180" />
                    <el-table-column prop="value" label="紫外值" />
                </el-table>
            </div>
            <div v-else>无数据</div>
        </el-dialog>
        
        <!-- 导出进度对话框 -->
        <el-dialog v-model="exportDialogVisible" title="数据导出进度" width="400px" :close-on-click-modal="false" :close-on-press-escape="false">
            <div class="export-progress-container">
                <div class="export-status">{{ exportStatus }}</div>
                <el-progress :percentage="exportProgress" :stroke-width="8" status="success" v-if="exportProgress > 0"></el-progress>
                <div class="export-tips" v-if="exportLoading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    <span>正在处理数据，请稍候...</span>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="exportDialogVisible = false" :disabled="exportLoading">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
    defineOptions({
      name: "ManageData"
    })
    import {Edit} from '@element-plus/icons-vue'
    import { Loading } from '@element-plus/icons-vue'
    import {onMounted,ref,reactive, ComponentInternalInstance} from 'vue'
    import {getCurrentInstance} from 'vue'
    import tool from '../../utils/tool'
    import { userStore } from '../../store/user'
    import { gatewayStore } from '../../store/gateway'
    import { channelNameDb } from '../../local/channelNameDb'
    import { ElMessageBox } from 'element-plus'
    import dayjs from 'dayjs'
    let store = userStore()
    let gateway_store = gatewayStore()
    interface GlobalProperties {
        $outsideHttp: any;
        $insideHttp: any;
        $downHttp: any;
        $adminHttp: any;
        $message: any;
        notifyWarning: (message: string, location?: string) => void;
    }
    let { proxy } = getCurrentInstance() as ComponentInternalInstance & { proxy: GlobalProperties };
    let currentPage = ref(1)
    let queryParmas = reactive({
        pageSize: 10,
        page: 1,
        queryDate: ""
    })
    let options = ref([])
    let stateList = ref([])
    let total = ref<number>(0)
    let selectDate = ref<string>('')
    
    // 导出进度相关变量
    const exportLoading = ref(false)
    const exportProgress = ref(0)
    const exportDialogVisible = ref(false)
    const exportStatus = ref('')
    
    // 设备名称映射
    const deviceNameMap = ref<Map<string, string>>(new Map())
    let propList = [
        {
            prop: "module_id",
            label: "message.id"
        },
        {
            prop: "uvc",
            label: "message.uv"
        },
        {
            prop: "inf",
            label: "message.inf"
        }
        ,
        {
            prop: "tem",
            label: "message.tem"
        },
        {
            prop: "hum",
            label: "message.hum"
        }
        ,
        {
            prop: "pre",
            label: "message.pre"
        }
    ]
     // 对时间函数的过滤
     let filterDate = (date:Date) => {
        return new Date(date).toLocaleDateString().replace(/\//g,"-")+' ' + new Date(date).toLocaleTimeString()
     }   
     // 禁用日期
     const disabledDate = (time: Date) => {
         return time.getTime() > Date.now()
     }
     
     // 获取设备名称
     const getDeviceName = (gatewayIp: string, moduleId: string) => {
         const key = `${gatewayIp}-${moduleId}`
         return deviceNameMap.value.get(key) || `监测点 ${moduleId}`
     }
     
     // 加载设备名称映射
     const loadDeviceNames = async () => {
         try {
             const nameMap = await channelNameDb.getAllNames()
             deviceNameMap.value = nameMap
         } catch (error) {
             console.error('加载设备名称失败:', error)
         }
     }

    onMounted(async () => {
        // 加载设备名称映射
        await loadDeviceNames()
        getStateList()
        // 获取指定下载的日期
        let {data:res} = await proxy.$adminHttp.get("/admin/downLoadDate")
         options.value = res.data
    })

    const getStateList = async () => {
    let {data: res} = await proxy.$adminHttp.get("/admin/getData",{
        params: queryParmas
    })
        total.value = res.data.total  //获取查询的总数
        // 为每条数据添加网关名称
        stateList.value = res.data.data.map((item: any) => {
            const gateway = gateway_store.gatewayList.find(g => g.id === item.gateway_id)
            return {
                ...item,
                gateway_name: gateway ? gateway.name : `网关${item.gateway_id || 'Unknown'}`
            }
        })    // 数据列表
    }
    // 按照日期进行查询
   const toSearch = () => {
        if (queryParmas.queryDate === '') return proxy.notifyWarning("请选择查询的日期")
        queryParmas.queryDate = new Date(queryParmas.queryDate).toLocaleDateString().replace(/\//g,'-')
        getStateList()
    }

    const handleSizeChange = (val:number) => {
        queryParmas.pageSize = val
        getStateList()
    }

    const handleCurrentChange = (val:number) => {
        queryParmas.page = val
        getStateList()
    }
    // 查询所有数据
    const searchAll = () => {
        queryParmas.page = 1
        queryParmas.pageSize = 10
        queryParmas.queryDate = ''
        getStateList()
    }
         // 下载excel数据
    const download = async () => {
        if (selectDate.value === '') return proxy.notifyWarning("请先选择日期")
        
        try {
            // 开始导出流程
            exportLoading.value = true
            exportProgress.value = 0
            exportDialogVisible.value = true
            exportStatus.value = '正在获取数据统计信息...'
            
            // 模拟进度更新
            const updateProgress = (progress: number, status: string) => {
                exportProgress.value = progress
                exportStatus.value = status
            }
            
            updateProgress(10, '正在获取数据统计信息...')
            let {data:result} = await proxy.$adminHttp.get("/admin/getItem?date=" + selectDate.value)
            store.computeNum(result.total)
            
            updateProgress(30, '正在请求导出数据...')
            let {data:res} = await proxy.$downHttp.post("/admin/downloadRunDate",{date: selectDate.value})
            
            updateProgress(50, '正在处理数据格式...')
            
            // 处理导出数据，使其与页面显示一致
             const processedData = res.data.map((item: any) => {
                 // 调试信息
                 console.log('处理数据项:', item)
                 console.log('当前网关列表:', gateway_store.gatewayList)
                 
                 // 优先通过gateway_ip查找网关名称
                 let gatewayName = gateway_store.gatewayNameMap(item.gateway_ip)
                 
                 // 如果通过IP找不到，尝试通过gateway_id查找
                 if (!gatewayName && item.gateway_id) {
                     const gateway = gateway_store.gatewayList.find(g => g.id === item.gateway_id)
                     gatewayName = gateway ? gateway.name : ''
                 }
                 
                 // 如果还是找不到，使用默认值
                 if (!gatewayName) {
                     gatewayName = "网关未连接"
                 }
                 
                 const deviceName = getDeviceName(item.gateway_ip, item.module_id)
                 
                 console.log('最终网关名称:', gatewayName)
                 
                 // 处理时间字段 - 导出数据可能有不同的时间字段格式
                  let timeDisplay = ''
                  if (item.createdAt) {
                      timeDisplay = filterDate(item.createdAt)
                  } else if (item.date && item.time) {
                      timeDisplay = item.date + ' ' + item.time
                  } else {
                      timeDisplay = '时间未知'
                  }
                  
                  return {
                      ...item,
                      createdAt: timeDisplay,
                      gateway_display: `${gatewayName} ${item.gateway_ip}`,
                      device_name: deviceName
                  }
             })
             
            updateProgress(80, '正在生成Excel文件...')
            
            // 添加延迟以显示进度
            await new Promise(resolve => setTimeout(resolve, 500))
            
            tool.tool.xlsx(processedData,{
                createdAt: "时间",
                gateway_display: "网关", 
                device_name: "设备名称",
                pre: "压力",
                inf: "红外",
                uvc: "紫外",
                tem: "温度",
                hum: "湿度",
            },selectDate.value)
            
            updateProgress(100, '导出完成！')
            
            // 延迟关闭对话框
            setTimeout(() => {
                exportDialogVisible.value = false
                exportLoading.value = false
                exportProgress.value = 0
                exportStatus.value = ''
            }, 1500)
            
        } catch (error) {
            console.error('导出失败:', error)
            exportStatus.value = '导出失败，请重试'
            exportLoading.value = false
            
            // 3秒后关闭对话框
            setTimeout(() => {
                exportDialogVisible.value = false
                exportProgress.value = 0
                exportStatus.value = ''
            }, 3000)
        }
   }

       // 测试缓存组件
    import { onActivated } from 'vue';
     onActivated(() => {
        console.log("缓存组件")
     })

    const uvcDialogVisible = ref(false)
    const uvcDetail = ref<{time:string,value:number}[]>([])
    let uvcBaseTime = ref('')

    function showUvcDetail(row:any) {
        // 主时间
        const baseTime = row.createdAt || row.time || row.date
        uvcBaseTime.value = baseTime
        // 紫外值数组
        let arr = (row.uvc + '').split(',').map(Number)
        uvcDetail.value = arr.map((v,i) => ({
            time: dayjs(baseTime).add(i*100,'ms').format('YYYY-MM-DD HH:mm:ss.SSS'),
            value: v
        }))
        uvcDialogVisible.value = true
    }
</script>

<style lang="less" scoped>
.container {
    background-color: #fff;
    padding: 0 20px;
    height: calc(100vh - 80px); /* 计算总高度 */
    display: flex;
    flex-direction: column;
}
.tool {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0; /* 防止工具栏被压缩 */
    .search {
        margin-top: 20px;
        .add {
            margin-right: 10px;
        }
        .query {
            margin-left: 10px;
        }
     }
   }
    
 .table {
    display: flex;
    flex-direction: column;
    margin-top: 10px;
    overflow: hidden; /* 防止溢出 */
    min-height: 0; /* 确保 flex 子项能够收缩 */
    .table-container {
        flex: 1; /* 占据大部分空间 */
        overflow: hidden;
        min-height: 0; /* 确保 flex 子项能够收缩 */
        
        /* 表格滚动样式 */
        :deep(.el-table) {
            height: auto !important;
        }
        
        :deep(.el-table__body-wrapper) {
            overflow-y: auto !important;
            max-height: calc(100vh - 280px); /* 确保表格主体不会超出视口 */
        }
    }
    
    .pagination-wrapper {
        flex-shrink: 0; /* 确保分页器始终可见 */
        padding: 15px 0;
        border-top: 1px solid #ebeef5;
        background: #fafafa;
        margin-bottom: 20px; /* 增加底部间距 */
        
        .el-pagination {
            display: flex;
            justify-content: center;
        }
    }
 }
 
 .downloadExe {
    width: 15%;
    display: flex;
 }

 /* 导出进度对话框样式 */
 .export-progress-container {
    padding: 20px 0;
    
    .export-status {
        margin-bottom: 15px;
        font-size: 14px;
        color: #606266;
        text-align: center;
    }
    
    .export-tips {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 15px;
        color: #909399;
        font-size: 13px;
        
        .el-icon {
            margin-right: 8px;
            font-size: 16px;
        }
    }
 }
</style>